package com.yuhs.zixing.study.thread.juc.code001;

import java.util.concurrent.TimeUnit;

/**
 * @description 线程的几个基本方法
 * @author: yuhs
 * @date 2021/11/17 8:36 下午
 */
public class C03_Sleep_Yield_Join {

    static void testSleep() {
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                System.out.println(Thread.currentThread().getName() + " 睡眠 " + i);
                try {
                    TimeUnit.MILLISECONDS.sleep(500);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    static void testYield() {

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                System.out.println(Thread.currentThread().getName() + " A " + i);
                if (i % 2 == 0) {
                    Thread.yield();
                }
            }
        }).start();
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                System.out.println(Thread.currentThread().getName() + " B " + i);
                if (i % 2 == 0) {
                    Thread.yield();
                }
            }
        }).start();
    }

    static void testJoin() {
        Thread thread1 = new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                System.out.println(Thread.currentThread().getName() + " JoinA " + i);
                try {
                    TimeUnit.MILLISECONDS.sleep(5000);

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });

        Thread thread2 = new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                System.out.println(Thread.currentThread().getName() + " JoinB " + i);
                try {
                    if (i == 5) {
                        System.out.println("join前线程状态 " + Thread.currentThread().getState());
                        thread1.join();
                        System.out.println("join后线程状态 " + Thread.currentThread().getState());
                    }
                    TimeUnit.MILLISECONDS.sleep(500);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        thread1.start();
        thread2.start();

    }

    public static void main(String[] args) {
//        testSleep();
//        testYield();
        testJoin();
    }
}
